<template>
  <div class="wrap-container">
    <div class="search_box">
      <div class="search_tit">订单查询</div>
      <el-form :inline="true" label-position="left" label-width="76px">
        <el-form-item label="订单编号">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="会员姓名">
          <el-input
            v-model="queryParams.realName"
            placeholder="请输入会员姓名"
            clearable
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="会员类型">
          <el-select
            v-model="queryParams.memberType"
            placeholder="请选择会员类型"
            clearable
            filterable
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in memberTypes"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="预约时段">
          <el-time-select
            placeholder="请选择开始时间"
            v-model="queryParams.timeStart"
            :picker-options="{
              start: '00:00',
              step: '00:60',
              end: '24:00',
              maxTime: queryParams.timeEnd,
            }"
            style="width: 120px"
          >
          </el-time-select>
          <el-time-select
            placeholder="请选择结束时间"
            v-model="queryParams.timeEnd"
            :picker-options="{
              start: '00:00',
              step: '00:60',
              end: '24:00',
              minTime: queryParams.timeStart,
            }"
            style="width: 120px"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item label="订单来源">
          <el-select v-model="queryParams.source" placeholder="请选择订单来源" clearable filterable>
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in orderSource"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域选择">
          <el-cascader
            filterable
            clearable
            :options="areaTree"
            v-model="addressId"
            @change="handleChange"
            placeholder="请选择区域"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="场馆类型">
          <el-select
            v-model="queryParams.stadiumType"
            placeholder="请选择场馆类型"
            clearable
            filterable
          >
            <el-option
              :label="item.dictLabel"
              :value="item.dictValue"
              v-for="item in dictTypeList"
              :key="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券类型">
          <el-select
            v-model="queryParams.couponType"
            placeholder="请选择优惠券类型"
            clearable
            filterable
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in couponTypes"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input
            v-model="queryParams.orderPhone"
            placeholder="请输入手机号码"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="订单日期">
          <el-date-picker
            v-model="queryParams.orderTime"
            type="date"
            placeholder="请选择订单日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <div style="display: flex; justify-content: flex-end">
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="reset">重置</el-button>
            <!-- <el-button>导出</el-button> -->
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="table_box">
      <div class="tabs_box">
        <el-tabs v-model="tabsVal" @tab-change="handleClick">
          <el-tab-pane
            :label="`${item.label}`"
            :name="item.value"
            v-for="item in tabsList"
            :key="item.value"
          >
            <template #label>
              <span
                :class="{
                  tabs_animation: item.value == 8 || item.value == 9,
                }"
              >
                {{ item.label }}
                <el-badge
                  v-if="item.count != 0"
                  :value="item.count"
                  :class="[
                    'item',
                    {
                      badge_animation:
                        (item.value == 8 && item.value > 0) || (item.value == 9 && item.value > 0),
                    },
                  ]"
                  :type="
                    item.value == 2 || item.value == 5 || item.value == 8 || item.value == 9
                      ? 'danger'
                      : 'info'
                  "
                ></el-badge>
              </span>
            </template>
          </el-tab-pane>
        </el-tabs>
        <div class="handle_btn">
          <el-button
            class="del_btn"
            type="primary"
            v-hasPermi="['sys:order:btn_add']"
            @click="handleAddOrder"
            >新建订单</el-button
          >
          <el-button class="del_btn" v-hasPermi="['sys:order:btn_remove']" @click="handleDel(1)"
            >批量删除</el-button
          >
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName"
        :cell-class-name="tableCellClass"
        border
      >
        <el-table-column type="selection" width="50"> </el-table-column>
        <el-table-column label="订单编号" prop="orderNo" width="180" />
        <el-table-column label="区域" prop="areaName" width="80" />
        <el-table-column label="订单来源" prop="source" width="90" />
        <el-table-column label="预约场馆" prop="stadiumName" width="170" show-overflow-tooltip />
        <!-- <el-table-column label="运动类型" prop="stadiumType" width="90" /> -->
        <el-table-column label="预约时段" width="290">
          <template #default="{ row }">
            <p v-for="(item, index) in row.bulletinList" :key="index">
              {{ item }}
            </p>
          </template>
        </el-table-column>
        <el-table-column label="会员姓名" prop="realName" width="90" />
        <!-- <el-table-column label="会员类型" prop="memberType" width="90" />
        <el-table-column label="会员等级 " prop="memberLevel" width="90" /> -->
        <el-table-column label="订单金额" prop="orderMoney" width="90" />
        <el-table-column label="优惠券类型" prop="couponType" width="100" :formatter="formatter" />
        <el-table-column label="实付金额" prop="paymentAmount" width="90" :formatter="formatter" />
        <el-table-column label="订单状态" prop="orderFlag" width="120">
          <template #default="{ row }">
            <span style="color: #0988fb" v-if="row.orderFlag == 1">待支付</span>
            <span style="color: #ff8d1a" v-else-if="row.orderFlag == 2">待核销</span>
            <span v-else-if="row.orderFlag == 3">待评价</span>
            <span style="color: #00baad" v-else-if="row.orderFlag == 5">已完成</span>
            <span style="color: #a6a6a6" v-else-if="row.orderFlag == 4">已取消</span>
            <span style="color: #cc0001" v-else-if="row.orderFlag == 6">退款中</span>
            <span style="color: #cc0001" v-else-if="row.orderFlag == 7">已退款</span>
            <span style="color: #00f303" v-else-if="row.orderFlag == 8">待确认</span>
            <template v-else-if="row.orderFlag == 9">
              <p class="text-color-D43030">已超时</p>
              <template v-if="row.orderRecordId == null">
                <p class="text-color-D43030 text-xs">
                  {{
                    row.outTitle == null || row.outTitle >= 60
                      ? '已过最后预订时间'
                      : `超时${row.outTitle}分钟`
                  }}
                </p>
              </template>
              <template v-else>
                <p class="text-color-D43030 text-xs">已处理</p>
              </template>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="订单日期" prop="paymentTime" width="150" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <div class="table_btn flex">
              <el-button
                class="primary_text"
                type="text"
                v-hasPermi="['sys:order:btn_view']"
                @click="handleDetail(row.id)"
                >查看</el-button
              >
              <div v-show="row.orderFlag == 8">
                <el-button
                  class="primary_text"
                  type="text"
                  v-hasPermi="['sys:order:btn_sure']"
                  @click="handleSure(row.id)"
                  style="margin-left: 12px"
                  >确认</el-button
                >
              </div>
              <div v-show="row.orderFlag == 9 && row.orderRecordId == null">
                <el-button
                  class="primary_text"
                  type="text"
                  v-hasPermi="['sys:order:btn_handle']"
                  @click="handleDeal(row.id)"
                  style="margin-left: 12px"
                  >处理</el-button
                >
              </div>
              <div
                v-show="
                  row.orderFlag == 2 ||
                  row.orderFlag == 3 ||
                  row.orderFlag == 5 ||
                  row.orderFlag == 8 ||
                  row.orderFlag == 9
                "
              >
                <el-button
                  class="red_text"
                  type="text"
                  v-hasPermi="['sys:order:btn_cancel']"
                  @click="handleCancel(row.id)"
                  style="margin-left: 12px"
                  >取消</el-button
                >
              </div>
              <!-- <el-button type="text" @click="handleUpdate(scope.row)"
                >编辑</el-button
              > -->
              <el-button
                type="text"
                v-hasPermi="['sys:order:btn_remove']"
                @click="handleDel(0, row.id)"
                style="margin-left: 12px"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
      <CancelOrder
        :isShow="cancelVisible"
        :orderId="orderId"
        pageType="order"
        @close="cancelVisible = false"
        @success="cancelSuccess"
      ></CancelOrder>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listData } from '@/api/system/dict/data'
import { getAreaTree } from '@/api/stadium/stadium'
import { getOrderList, getOrderCount, deleteOrder, timeOutOrderDispose } from '@/api/order/order.js'
import { confirmOrder } from '@/api/business/business.js'
import CancelOrder from '@/components/common/cancelOrder.vue'
import { useStore } from 'vuex'

defineOptions({
  name: 'List',
})

interface MemberType {
  id: number
  name: string
}

interface DictType {
  dictLabel: string
  dictValue: string
}

interface CouponType {
  id: number
  name: string
}

interface OrderSource {
  id: number
  name: string
}

interface QueryParams {
  pageNum: number
  pageSize: number
  orderNo: string | null
  memberType: number | null
  realName: string | null
  source: number | null
  stadiumType: string | null
  couponType: number | null
  orderPhone: string | null
  orderTime: string | null
  stateId?: number
  cityId?: number
  districtId?: number
  timeStart?: string
  timeEnd?: string
}

interface TabItem {
  label: string
  value: number
  count: number
}

interface TableRow {
  id: number
  orderNo: string
  areaName: string
  source: string
  stadiumName: string
  bulletinList: string[]
  realName: string
  orderMoney: number
  couponType: string
  paymentAmount: number
  orderFlag: number
  paymentTime: string
  orderRecordId: number | null
  outTitle: number | null
  maxOrderTime: string
  _timerId?: number
}

const store = useStore()
const router = useRouter()

const loading = ref(false)
const memberTypes = ref<MemberType[]>([
  {
    id: 1,
    name: '普通用户',
  },
])
const dictTypeList = ref<DictType[]>([])
const couponTypes = ref<CouponType[]>([
  { id: 1, name: '折扣券' },
  { id: 2, name: '全额券' },
  { id: 3, name: '满减券' },
])
const areaTree = ref([])
const orderSource = ref<OrderSource[]>([{ id: 0, name: '小程序' }])
const addressId = ref<number[]>([])

const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  orderNo: null,
  memberType: null,
  realName: null,
  source: null,
  stadiumType: null,
  couponType: null,
  orderPhone: null,
  orderTime: null,
})

const total = ref(0)
const tabsList = ref<TabItem[]>([])
const tabsVal = ref<string>('')
const tableData = ref<TableRow[]>([])
const multipleSelection = ref<TableRow[]>([]) //表格多选的值
const cancelVisible = ref(false)
const orderId = ref<number | null>(null)

// 订单列表超时订单计时
const startTimer = (order: TableRow) => {
  if (order._timerId) return // 防止重复启动
  const timerId = setInterval(() => {
    if (order.orderFlag == 9 && (order.outTitle ?? 0) < 60 && order.orderRecordId == null) {
      const maxOrderStartTime = new Date(order.maxOrderTime).getTime()
      const now = new Date().getTime()
      const diff = now - maxOrderStartTime
      const newTotal = Math.max(0, diff)
      const newMinutes = Math.floor(newTotal / 1000 / 60)
      order.outTitle = newMinutes
      if (newMinutes > 60) {
        clearInterval(timerId)
        delete order._timerId
      }
    }
  }, 1000) as unknown as number
  order._timerId = timerId
}

// 清除计时器
const stopAllTimers = () => {
  tableData.value.forEach((order) => {
    if (order._timerId) {
      clearInterval(order._timerId)
      delete order._timerId
    }
  })
}

// 订单列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getOrderList({
      ...queryParams,
      ...{ orderFlag: tabsVal.value == '0' ? '' : tabsVal.value },
    })
    tableData.value = res.rows
    total.value = res.total
    loading.value = false
    tableData.value.forEach((order) => startTimer(order))
  } catch (error) {
    console.error(error)
    loading.value = false
  }
}

// 订单统计
const getCount = async () => {
  try {
    const { data } = await getOrderCount(queryParams)
    tabsList.value = data
  } catch (error) {
    console.error(error)
  }
}

//获取场馆类型
const getDictTypeList = async () => {
  try {
    const params = {
      pageNum: 1,
      pageSize: 99,
      dictType: 'site_type',
    }
    const res = await listData(params)
    dictTypeList.value = res.rows
  } catch (error) {
    console.error(error)
  }
}

// 获取省市区数据
const getArea = async () => {
  try {
    const { data } = await getAreaTree()
    areaTree.value = data
  } catch (error) {
    console.error(error)
  }
}

// 省市区选择
const handleChange = (value: any) => {
  if (value && value.length >= 3) {
    queryParams.stateId = value[0]
    queryParams.cityId = value[1]
    queryParams.districtId = value[2]
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
  getCount()
}

// 重置
const reset = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    memberType: null,
    realName: null,
    source: null,
    stadiumType: null,
    couponType: null,
    orderPhone: null,
    orderTime: null,
  })
  getList()
  getCount()
}

// 选项卡切换
const handleClick = () => {
  queryParams.pageNum = 1
  getList()
  getCount()
}

// 表格多选
const handleSelectionChange = (val: TableRow[]) => {
  multipleSelection.value = val
}

// 查看详情
const handleDetail = (id: number) => {
  router.push({
    path: '/order/detail',
    query: { id },
  })
}

// 编辑
const handleUpdate = () => {}

// 删除
const handleDel = (type: number, id?: number) => {
  let ids = ''
  if (type == 1) {
    ids = multipleSelection.value.map((item) => item.id).join(',')
  } else {
    ids = id?.toString() || ''
  }
  if (ids == '') {
    ElMessage.error('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm('是否确认删除选中的数据项？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await deleteOrder(ids)
        getList()
        getCount()
        ElMessage.success('删除成功')
      } catch (error) {
        console.error(error)
      }
    })
    .catch(() => {})
}

const formatter = (row: TableRow, column: any, cellValue: any) => {
  // 如果单元格值为空或为 null，返回 '--'
  return cellValue || '--'
}

// 取消订单
const handleCancel = (id: number) => {
  orderId.value = id
  cancelVisible.value = true
}

// 取消成功
const cancelSuccess = (msg: string) => {
  cancelVisible.value = false
  getList()
  getCount()
  ElMessage.success(msg)
}

// 新建订单
const handleAddOrder = () => {
  router.push({ path: '/order/add' })
}

// 确认接单
const handleSure = (id: number) => {
  ElMessageBox.confirm('是否确认接单？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await confirmOrder({
          orderId: id,
          userId: store.state.user.id,
        })
        getCount()
        getList()
        ElMessage.success('操作成功')
      } catch (error) {
        console.error(error)
      }
    })
    .catch(() => {})
}

// 设置表格行样式
const tableRowClassName = ({ row, rowIndex }: { row: TableRow; rowIndex: number }) => {
  if (row.orderFlag == 9 && row.orderRecordId == null) {
    if (row.outTitle == null || row.outTitle >= 60) {
      return 'grey-row'
    } else {
      return 'red-row'
    }
  }
  return ''
}

const tableCellClass = ({
  row,
  column,
  rowIndex,
  columnIndex,
}: {
  row: TableRow
  column: any
  rowIndex: number
  columnIndex: number
}) => {
  if (row.orderRecordId != null && column.property == 'orderNo') {
    return 'order_style'
  }
  return ''
}

// 处理已超时订单
const handleDeal = (id: number) => {
  ElMessageBox.confirm('是否确认已处理？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await timeOutOrderDispose(id)
        getList()
        ElMessage.success('操作成功')
      } catch (error) {
        console.error(error)
      }
    })
    .catch(() => {})
}

onMounted(() => {
  getList()
  getCount()
  getDictTypeList()
  getArea()
})

onBeforeUnmount(() => {
  stopAllTimers()
})
</script>

<style lang="scss" scoped>
.search_box {
  padding-bottom: 0;
}
.table_box {
  position: relative;
  .tabs_box {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    margin-bottom: 15px;
    padding-top: 6px;
    :deep(.el-tabs) {
      flex: 1;
      .el-tabs__header {
        margin: 0;
      }
      .tabs_animation {
        // animation: blink 1s infinite; /* 应用动画 */
      }
    }
  }
  .handle_btn {
    margin-left: 35px;
  }
}
:deep(.el-table .el-table__body td .cell .line-limit-length:empty::after) {
  content: '--';
}
:deep(.red-row) {
  & > td.el-table__cell {
    background: rgba(212, 48, 48, 0.15) !important;
  }
  &.hover-row {
    & > td.el-table__cell {
      background: rgba(212, 48, 48, 0.15) !important;
    }
  }
}
:deep(.grey-row) {
  & > td.el-table__cell {
    background: #e5e5e5 !important;
  }
  &.hover-row {
    & > td.el-table__cell {
      background: #e5e5e5 !important;
    }
  }
}
:deep(.order_style) {
  color: #0988fb !important;
}
.badge_animation {
  animation: blink 1.5s infinite;
}
@keyframes bounce {
  0%,
  100% {
    top: 0;
    transform: translateY(0);
  }
  50% {
    transform: translateY(-8px); /* 调整这个值以改变跳动的高度 */
  }
}
@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}
</style>
